package xyz.xpman.prisonerfitness.activity.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.Collections;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import xyz.xpman.prisonerfitness.util.ActivityUtil;
import xyz.xpman.prisonerfitness.util.ImgUtil;
import xyz.xpman.prisonerfitness.util.ScreenUtil;
import xyz.xpman.prisonerfitness.util.ToastUtil;


@SuppressWarnings("unused")
public class BaseActivity extends AppCompatActivity {


    public Point getWindowsSize(@NotNull final Activity activity) {
        return ScreenUtil.getWindowsSize(activity);
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    public String getExtStorageAbsolutePath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    public String getExtStoragePath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    protected Intent newIntent(Class<?> cls) {
        return new Intent(this, cls);
    }



    protected <T> T getIntentExtra(String name) {
        return (T) getIntent().getSerializableExtra(name);
    }

    protected <T> T getIntentExtra(String name, T defaultValue) {
        Serializable serializableExtra = getIntent().getSerializableExtra(name);

        if (null == serializableExtra) {
            return defaultValue;
        }

        return (T) serializableExtra;
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    protected void showSameSizeImg(
            @NotNull Activity activity, int imgId, int imageViewId) {

        Bitmap bitmap = ImgUtil.getAppropriateImg(activity, imgId);

        ((ImageView) findViewById(imageViewId)).setImageBitmap(bitmap);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    public void fullScreen() {
        ActivityUtil.fullScreen(this);
    }


    /**
     * 隐藏状态栏
     */
    @RequiresApi(api = Build.VERSION_CODES.P)
    protected void hideStatusBar(){
        ActivityUtil.hideStatusBar(this);
    }


    /**
     * 隐藏title
     */
    protected void hideTitleBar(){
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    @SuppressLint("ObsoleteSdkInt")
    protected void hideBottomUIMenu() {
        ActivityUtil.hideBottomUIMenu(this);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    private static final int TIME_EXIT = 2000;
    // 第一次点击事件发生的时间
    private long existTime = 0;

    protected interface KeyBackProcess {
        boolean run();
    }

    protected boolean processKeyBack(int keyCode, KeyEvent event,
                                  @NotNull KeyBackProcess process) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            boolean bool = process.run();

            if (bool) {
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected boolean twoKeyBackToExist(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            processKeyBackToExist();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    protected boolean keyToBack(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击两次返回退出app
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void processKeyBackToExist() {
        if ((System.currentTimeMillis() - existTime) > TIME_EXIT) {
            ToastUtil.showText(this, "再按一次退出程序");
            existTime = System.currentTimeMillis();
        } else {
            processBeforeExit();
            finish();
        }
    }


    protected void processBeforeExit() {

    }

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    protected void clickToActivity(
            int id, @NotNull Context packageContext, @NotNull Class<?> target) {

        findViewById(id).setOnClickListener(view->
                toActivity(packageContext, target));
    }

    /**
     * 返回上个页面
     * @param id 组件id
     */
    protected void clickToGoBack(int id) {
        findViewById(id).setOnClickListener(view-> finish());
    }

    // 有点浪费资源
    protected void task(@NotNull Runnable runnable, long delay) {
        // 定时任务，只使用一次
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runnable.run();
            }
        }, delay);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    protected void toActivity(@NotNull Class<?> target, long delay) {

        toActivity(this, target, delay);
    }

    protected void toActivity(
            @NotNull Context packageContext, @NotNull Class<?> target, long delay) {

        task(() -> toActivity(packageContext, target), delay);
    }



    protected void toActivity(@NotNull Class<?> target) {

        toActivity(this, target);
    }


    protected void toActivity(
            @NotNull Context packageContext, @NotNull Class<?> target) {

        startActivity(new Intent(packageContext, target));
    }



    // TextView process
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    // default 4 indentation
    @RequiresApi(api = Build.VERSION_CODES.O)
    protected void addIndentation(@NotNull TextView textView) {
        addIndentation(textView, String.valueOf(textView.getText()), 4);
    }

    // default 4 indentation
    @RequiresApi(api = Build.VERSION_CODES.O)
    protected void addIndentation(@NotNull TextView textView, @NotNull String text) {
        addIndentation(textView, text, 4);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("SetTextI18n")
    protected void addIndentation(@NotNull TextView textView,
                                  @NotNull String text,
                                  int count) {

        textView.setText(getIndentation("\t", count) + text);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    protected String getIndentation(@NotNull String repeat, int count) {
        return getIndentation(repeat, count, "");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    protected String getIndentation(@NotNull String repeat, int count, @NotNull String delimiter) {
        return String.join(delimiter, Collections.nCopies(count, repeat));
    }




    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    protected void enabledHomeAsUp() {
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
    }


    protected boolean processMenuItemForBack(MenuItem item) {
        // 点击返回图标事件
        if (item.getItemId() == android.R.id.home) {
            callBack(item);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    protected void callBack(MenuItem item) {
        callBack();
    }

    protected void callBack() {
        this.finish();
    }


    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -



    @SuppressLint("RtlHardcoded")
    protected void popupWindowToCenter(@NotNull View parentView, int layoutId) {
        //创建
        PopupWindow popupWindow = new PopupWindow(this);

        //设置
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(LayoutInflater.from(this).inflate(layoutId, null));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

        //显示在控件下面
//        popupWindow.showAsDropDown(buttonUseCar);
        //显示父控件中的指定位置
        popupWindow.showAtLocation(parentView, Gravity.TOP | Gravity.LEFT, 0, 100);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

/*
    public static void scaleImage(final Activity activity, final View view, int drawableResId) {

        // 获取屏幕的高宽
        Point outSize = new Point();
        activity.getWindow().getWindowManager().getDefaultDisplay().getSize(outSize);

        // 解析将要被处理的图片
        Bitmap resourceBitmap = BitmapFactory.decodeResource(activity.getResources(), drawableResId);

        if (resourceBitmap == null) {
            return;
        }

        // 开始对图片进行拉伸或者缩放

        // 使用图片的缩放比例计算将要放大的图片的高度
        int bitmapScaledHeight = Math.round(resourceBitmap.getHeight() * outSize.x * 1.0f / resourceBitmap.getWidth());

        // 以屏幕的宽度为基准，如果图片的宽度比屏幕宽，则等比缩小，如果窄，则放大
        final Bitmap scaledBitmap = Bitmap.createScaledBitmap(resourceBitmap, outSize.x, bitmapScaledHeight, false);

        view.getViewTreeObserver().addOnPreDrawListener(() -> {
            //这里防止图像的重复创建，避免申请不必要的内存空间
            if (scaledBitmap.isRecycled())
                //必须返回true
                return true;


            // 当UI绘制完毕，我们对图片进行处理
            int viewHeight = view.getMeasuredHeight();


            // 计算将要裁剪的图片的顶部以及底部的偏移量
            int offset = (scaledBitmap.getHeight() - viewHeight) / 2;


            // 对图片以中心进行裁剪，裁剪出的图片就是非常适合做引导页的图片了
            Bitmap finallyBitmap = Bitmap.createBitmap(scaledBitmap, 0, offset, scaledBitmap.getWidth(),
                                            scaledBitmap.getHeight() - offset * 2);


            if (!finallyBitmap.equals(scaledBitmap)) {//如果返回的不是原图，则对原图进行回收
                scaledBitmap.recycle();
                System.gc();
            }


            // 设置图片显示
            view.setBackgroundDrawable(new BitmapDrawable(context.getResources(), finallyBitmap));
            return true;
        });
    }
*/


}
